package com.yazi.mxz.person.controller;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.myframework.smhj.common.exception.MyException;
import com.myframework.smhj.common.exception.MyIllegalArgumentException;
import com.myframework.smhj.jackson.result.ObjectResult;
import com.myframework.smhj.jackson.result.StatusResult;
import com.yazi.mxz.common.entity.beans.Company;
import com.yazi.mxz.common.entity.beans.CompanyMember;
import com.yazi.mxz.common.entity.beans.Member;
import com.yazi.mxz.common.entity.beans.Store;
import com.yazi.mxz.common.entity.beans.StoreMember;
import com.yazi.mxz.common.service.MemberService;
import com.yazi.mxz.person.common.Principal;
import com.yazi.mxz.person.common.Realm;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller("memberController")
@RequestMapping("/member")
public class MemberController extends BaseController {
	private static Logger log = LoggerFactory.getLogger(MemberController.class);
	@Resource
	MemberService memberService;

	@RequestMapping("/register")
	public String register() {
		log.debug("进入注册页面");
		logoutDo();
		return "member_register";
	}

	@RequestMapping("/login")
	public String login(Model model) {
		log.debug("进入登录页面");
		Member member = getMember();
		model.addAttribute("member", member);
		return "member_login";
	}

	@RequestMapping("/logoutDo")
	public String logoutDo() {
		Member loginMember = getMember();
		if (null == loginMember) {
			log.debug("注销登录: name=null");
		} else {
			log.debug("注销登录: name={}", loginMember.getName());
		}
		SecurityUtils.getSubject().logout();
		return REDIRECT_INDEX;
	}

	@RequestMapping("/checkName")
	@ResponseBody
	public Map<String, String> checkName(RegisterInfo regInfo) {
		log.debug("验证注册用户名");
		String msg = null;
		try {
			String name = regInfo.getMember().getName();
			if (null == name || name.isEmpty()) {
				throw new MyIllegalArgumentException();
			}
			Member member = new Member();
			member.setName(name);
			List<Member> list = memberService.list(member);
			if (list.size() > 0) {
				msg = "已经被使用";
			}
		} catch (MyException e) {
			msg = e.getMessage();
		} catch (Exception e) {
			log.debug("验证用户名异常:", e);
			msg = e.getMessage();
		} 
		Map<String, String> map = new HashMap<String, String>();
		map.put(null == msg ? "ok" : "error", msg);
		return map;
	}

	@RequestMapping("/registerDo/json")
	@ResponseBody
	public StatusResult registerDoJson(RegisterInfo regInfo) {
		log.debug("提交注册");
		StatusResult jsonResult = new StatusResult();
		try {
			if (!checkCaptcha(regInfo.getCaptcha())) {
				jsonResult.setFailMessage("验证码不正确");
				return jsonResult;
			}
			if (regInfo.getType() == 1) {
				memberService.add(regInfo.getMember(), regInfo.getCompany());
			} else {
				memberService.add(regInfo.getMember());
			}
			jsonResult.setOkMessage("ok");
		} catch (MyException e) {
			log.debug("注册失败: {}", e.getMessage());
			jsonResult.setFailMessage(e.getMessage());
		} catch (DataIntegrityViolationException e) {
			log.debug("注册失败: {}", "用户名已经被注册");
			jsonResult.setFailMessage("用户名已经被注册");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			jsonResult.setErrorMessage(e.getMessage());
		}
		return jsonResult;
	}

	@RequestMapping("/loginDo/json")
	@ResponseBody
	public ObjectResult<String> loginDoJson(Member member, boolean isRememberMe,
			HttpServletRequest request) {
		log.debug("登录");
		ObjectResult<String> jsonResult = new ObjectResult<String>();
		try {
			UsernamePasswordToken token = new UsernamePasswordToken();
			token.setUsername(member.getName());
			token.setPassword(member.getPassword().toCharArray());
			token.setRememberMe(isRememberMe);
			Subject subject = SecurityUtils.getSubject();
			subject.login(token);
			
			Principal principal = (Principal)subject.getPrincipal();
			member = memberService.one(principal.getMember().getMemberId());
			
			// 跳转地址
			String successUrl = null;
			
			Iterator<StoreMember> smit = member.getStoreMembers().iterator();
			if (smit.hasNext()) {
				Store store = smit.next().getStore();
				store.getName();// 调一个方法触发懒加载
				principal.setStore(store);
				Company com = store.getCompany();
				com.getName();// 调一个方法触发懒加载
				principal.setCompany(com);
			}
			Iterator<CompanyMember> cmit = member.getCompanyMembers().iterator();
			if (cmit.hasNext()) {
				Company com = cmit.next().getCompany();
				com.getName();// 调一个方法触发懒加载
				principal.setCompany(com);
			}
			
			SimplePrincipalCollection spc = new SimplePrincipalCollection(principal, Realm.class.getName());
			subject.runAs(spc);
			

			SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(request);
			if (savedRequest != null
					&& savedRequest.getMethod().equalsIgnoreCase(AccessControlFilter.GET_METHOD)
					&& savedRequest.getRequestUrl().indexOf("/json") == -1) {
				successUrl = savedRequest.getRequestUrl();
			}
			jsonResult.setResult(successUrl);
			jsonResult.setOk();
		} catch (AuthenticationException e) {
			log.debug("登录失败: {}", e.getMessage());
			jsonResult.setFailMessage("用户名或者密码错误");
		} catch (Exception e) {
			log.error("登录异常:", e);
			jsonResult.setErrorMessage(e.getMessage());
		}
		return jsonResult;
	}

	@RequestMapping(value = "/noPerms", headers = "X-Requested-With=XMLHttpRequest")
	@ResponseBody
	public StatusResult noPermsJson(HttpServletRequest request, Model model) {
		StatusResult jsonResult = new StatusResult();
		jsonResult.setFailMessage("您没有权限进行此操作!");
		return jsonResult;
	}

	@RequestMapping(value = "/noPerms", headers = "!X-Requested-With")
	public String noPerms(HttpServletRequest request, Model model) {
		return "member_noPerms";
	}

	public static class RegisterInfo {
		private Member member;
		private Company company;
		private String captcha;
		private int type;

		public Member getMember() {
			return member;
		}

		public void setMember(Member member) {
			this.member = member;
		}

		public Company getCompany() {
			return company;
		}

		public void setCompany(Company company) {
			this.company = company;
		}

		public String getCaptcha() {
			return captcha;
		}

		public void setCaptcha(String captcha) {
			this.captcha = captcha;
		}

		public int getType() {
			return type;
		}

		public void setType(int type) {
			this.type = type;
		}
	}

}
